//
//  GMBannerView.m
//  golfMaster
//
//  Created by snack on 14-7-26.
//  Copyright (c) 2014年 Master. All rights reserved.
//

#import "GMBannerView.h"
#import "GMBannerModel.h"
#import "UIImageView+WebCache.h"
#import "GMGradientImageView.h"
#import "GMString.h"
#import "UIView+Convenience.h"

#define AutoPlayTimeInterval    3
#define ScreenFrame [[UIScreen mainScreen ] bounds]


@interface GMBannerView () <UIScrollViewDelegate, UIGestureRecognizerDelegate>

@property (nonatomic, strong) NSArray *bannerArray;

@property (nonatomic, weak) IBOutlet UIScrollView *bannerScrollView;
@property (nonatomic, weak) IBOutlet UIView *translucentView;
@property (nonatomic, weak) IBOutlet UILabel *bannerTitleLabel;
@property (nonatomic, weak) IBOutlet UIPageControl *bannerPageControl;

@property (nonatomic, weak) IBOutlet NSLayoutConstraint *bannerPageControlWidth;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bannerTitleLabelBottem;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bannerPageControlRight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *horizontalSpacePageViewAndTitle;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bannerVideoBottom;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bannerVideoWidth;
@property (weak, nonatomic) IBOutlet UIImageView *bannerMaskImage;

@end


@implementation GMBannerView

#pragma mark -
#pragma mark - Property Method

- (void)setShowTitleView:(BOOL)showTitleView
{
    _showTitleView = showTitleView;
    
    if (showTitleView) {
        self.translucentView.hidden = NO;
        self.bannerTitleLabel.hidden = NO;
        self.bannerPageControl.hidden = NO;
    } else {
        self.translucentView.hidden = YES;
        self.bannerTitleLabel.hidden = YES;
        self.bannerPageControl.hidden = YES;
    }
}

- (void)setBannerArray:(NSArray *)bannerArray
{
    NSMutableArray *mArray = [bannerArray mutableCopy];
    if (bannerArray.count > 1) {
        [mArray addObject:bannerArray[0]];
        [mArray insertObject:bannerArray.lastObject atIndex:0];
    }
    _bannerArray = mArray;
}

#pragma config views
-(void)configTitleLabel{
    
    self.bannerTitleLabel.hidden=YES;
}

-(void)configTranslucentView{
    
    self.translucentView.hidden=YES;
}

#pragma mark -
#pragma mark - Public Method

- (void)configViewWithBannerArray:(NSArray *)array placeHolderImage:(UIImage *)placeHoler
{
    if (!array.count) {
        self.hidden = YES;
        return ;
    }
    
    [self configTitleLabel];
    [self configTranslucentView];

    self.bannerArray = array;
    self.bannerScrollView.contentSize = CGSizeMake(self.frameWidth * self.bannerArray.count, self.frame.size.height);
    
    for (int i = 0; i < self.bannerArray.count; i++) {
        GMGradientImageView*imageView = [[GMGradientImageView alloc] initWithFrame:self.bounds];
        imageView.frameX = i * self.frameWidth;
        [self.bannerScrollView addSubview:imageView];
        
        NSString *imageURLStr = ((GMBannerModel *)self.bannerArray[i]).imageURL;
        UIImage *placeHolderImage = placeHoler? placeHoler : PCImage(@"DefaultBannerImage");
        [imageView sd_setImageWithURL:PCURL(imageURLStr) placeholderImage:placeHolderImage];
    }
    
    self.bannerPageControl.numberOfPages = array.count;
    self.bannerPageControl.currentPage = 0;
    
    if (array.count == 1) {
        self.bannerPageControl.hidden = YES;
        self.bannerTitleLabel.text = [NSString stringWithFormat:@"%@",(([array firstObject])[@"title"])];
    }
    
    if (array.count > 1) {
        self.bannerPageControl.hidden = self.showTitleView? NO : YES;
        self.bannerPageControlWidth.constant = array.count * 16 - 8;
        [self turnToPageWithPageIndex:1 withAnimated:NO];
        
        if (self.autoPlay) {
            //if (self.autoPlayTimer.isValid) [self.autoPlayTimer invalidate];
            [self creatTimer];
           // [self pastTimer];
        }
    }

    self.hidden = NO;
}

- (void)showVideoIcon
{
    self.bannerVideoWidth.constant = 23.0;
    [self.superview layoutIfNeeded];
}

- (void)hiddenVideoIcon
{
    self.bannerVideoWidth.constant = 0.0;
    [self.superview layoutIfNeeded];
}

- (void)configTypeForForum
{
    self.bannerMaskImage.hidden = NO;
    self.bannerTitleLabel.shadowColor = PCColorOfRGB(0.0, 0.0, 0.0, 0.4);
    self.bannerTitleLabel.shadowOffset = CGSizeMake(1.5, 1.5);
    self.translucentView.hidden = YES;
    self.bannerTitleLabel.font = [UIFont boldSystemFontOfSize:18];
    self.bannerVideoBottom.constant = 24;
    self.bannerTitleLabelBottem.constant = 20.0;
    [self removeConstraint:self.horizontalSpacePageViewAndTitle];
    [self setEdge:self view:self.bannerTitleLabel attribute:NSLayoutAttributeRight constant:-8];
    self.bannerPageControlRight.constant = (SCREEN_W - self.bannerPageControl.frame.size.width)/2;
    [self.superview layoutIfNeeded];
}

- (void) setEdge:(UIView*)superview view:(UIView*)view attribute:(NSLayoutAttribute)attr constant:(CGFloat)constant
{
    [superview addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:attr relatedBy:NSLayoutRelationEqual toItem:superview attribute:attr multiplier:1.0 constant:constant]];
}

- (void)creatTimer
{
    if (self.bannerArray.count <= 1) {
        return;
    }
    if (!self.autoPlayTimer) {
        self.autoPlayTimer = [NSTimer scheduledTimerWithTimeInterval:AutoPlayTimeInterval target:self selector:@selector(autoScrollToNextPageCommon) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:self.autoPlayTimer forMode:NSRunLoopCommonModes];
    }
}

- (void)stopTimer{
    [self.autoPlayTimer setFireDate:[NSDate distantFuture]];
    if (self.autoPlayTimer){
        [self.autoPlayTimer invalidate];
        self.autoPlayTimer = nil;
    }
}

// 启动定时器
- (void)pastTimer
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(fireDataFormTimer) object:nil];
    [self performSelector:@selector(fireDataFormTimer) withObject:nil afterDelay:AutoPlayTimeInterval];
}

// 暂停定时器
- (void)futureTimer{
    [self.autoPlayTimer setFireDate:[NSDate distantFuture]];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(fireDataFormTimer) object:nil];
}

-(void)fireDataFormTimer{
    
//    if (!self.autoPlayTimer) {
//        self.autoPlayTimer = [NSTimer scheduledTimerWithTimeInterval:AutoPlayTimeInterval target:self selector:@selector(autoScrollToNextPageCommon) userInfo:nil repeats:YES];
//        [[NSRunLoop currentRunLoop] addTimer:self.autoPlayTimer forMode:NSRunLoopCommonModes];
//    }else{
//        [self.autoPlayTimer setFireDate:[NSDate distantPast]];
//    }
    
    [self.autoPlayTimer setFireDate:[NSDate distantPast]];

}

#pragma mark -
#pragma mark - Private Method

- (void)turnToPageWithPageIndex:(NSInteger)index withAnimated:(BOOL)animated
{
    //DLog(@"indexindexindex :%d",index);
    CGFloat newX = self.frame.size.width * index;
    [self.bannerScrollView setContentOffset:CGPointMake(newX, 0) animated:animated];
//    self.bannerTitleLabel.text = [self.bannerArray[index] bTitle];
    self.bannerTitleLabel.text = [NSString stringWithFormat:@"%@",((GMBannerModel *)self.bannerArray[index]).title];
    self.bannerPageControl.currentPage = index - 1;
    
//    if ([self.bannerArray[index] bBannerType] == GMBannerType_Video) {
//        [self showVideoIcon];
//    }else{
        [self hiddenVideoIcon];
//    }
}

#pragma mark -
#pragma mark - Initialization

- (instancetype)awakeAfterUsingCoder:(NSCoder *)aDecoder
{
    BOOL theLoadedViewWasJustAPlaceholder = (self.subviews.count == 0)? YES : NO;

    if (theLoadedViewWasJustAPlaceholder) {
        UINib *bannerNib = [UINib nibWithNibName:NSStringFromClass([self class]) bundle:nil];
        GMBannerView *bannerView = [[bannerNib instantiateWithOwner:nil options:nil] firstObject];
        return bannerView;
    }
    return self;
}

- (void)awakeFromNib
{
    self.hidden = YES;
    self.autoPlay = YES;
    self.showTitleView = YES;
}


#pragma mark -
#pragma mark - Timer Handle

- (void)autoScrollToNextPageCommon
{
    NSInteger currentIndex = self.bannerPageControl.currentPage + 1;
    [self turnToPageWithPageIndex:++currentIndex withAnimated:YES];
}


#pragma mark -
#pragma mark - ScrollView Delegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if (self.autoPlayTimer) {
        [self futureTimer];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (self.autoPlayTimer) {
        [self pastTimer];
    }
}

// called when setContentOffset/scrollRectVisible:animated: finishes. not called if not animating
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    int index = scrollView.contentOffset.x / self.frame.size.width;
    if (index >= self.bannerArray.count - 1) {
        [self turnToPageWithPageIndex:1 withAnimated:NO];
    }
}

// called when scroll view grinds to a halt
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    int index = scrollView.contentOffset.x / self.frame.size.width;
    [self turnToPageWithPageIndex:index withAnimated:NO];
    if (index >= self.bannerArray.count - 1) {
        [self turnToPageWithPageIndex:1 withAnimated:NO];
    }
    if (index <= 0) {
        [self turnToPageWithPageIndex:(self.bannerArray.count - 2) withAnimated:NO];
    }
}


#pragma mark -
#pragma mark - TapGesture Handle

- (IBAction)tapGestureHandleInBannerScrollView:(UITapGestureRecognizer *)sender
{
    if (self.bannerArray.count && [self.bDelegate respondsToSelector:@selector(bannerViewPressedAt:)]) {
        
//        NSString *titleValue=((GMBannerModel *)self.bannerArray[self.bannerPageControl.currentPage]).bSpread_title;
//        
//        if([NSString isEmptyString:titleValue]){
//            
//            titleValue=[NSString stringWithFormat:@"默认"];
//        }
//        //umeng自定义统计计数事件
//        [GMStatCustomEvent umengStatCountParamer:@"banner_ads" keyName:@"title" value:titleValue];

        [self.bDelegate bannerViewPressedAt:self.bannerPageControl.currentPage];
    }
}

@end
